package com.java.common.boot.advice;

import java.io.IOException;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.java.common.lang.annotation.Encrypt;
import com.java.common.lang.exception.BaseException;
import com.java.common.utils.crypto.RsaKit;

/**
 * 请求参数解密
 * 
 * @author yilabao
 * @date 2021年1月29日
 */
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(DecryptRequestBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        if (body == null) {
            return body;
        }

        try {
            BodyAdviceKit.resetSimpleObject(body, Encrypt.class, new BodyAdvice() {
                @Override
                public Object getAdviceFieldValue(Object fieldValue) throws Exception {
                    return RsaKit.decrypt(String.valueOf(fieldValue));
                }
            });
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new BaseException("数据解密异常");
        }

        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
            Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

}